package com.nativetalk.controller.app.found;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.common.Constants;
import com.nativetalk.common.Lang;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.Ip;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.service.found.insert.FoundChangeInsertService;
import com.nativetalk.service.found.search.FoundChangeSearchService;
import com.nativetalk.service.found.update.FoundChangeUpdateService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Map;

/**
 * Created by lizhun on 15/12/9.
 */
@Controller
public class FoundController {
    private static Logger logger = Logger.getLogger(FoundController.class);
    @Resource
    private FoundChangeSearchService foundChangeSearchService;
    @Resource
    private FoundChangeInsertService foundChangeInsertService;
    @Resource
    private FoundChangeUpdateService foundChangeUpdateService;

    /**
     * @return RetInfo
     * @Purpose 查看个人资金变动记录
     * @version 1.0
     * @time 2015-12-28
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/foundChange", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo foundChange(@RequestBody Map<String, String> map,
                               @RequestHeader(value = "token", required = true) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(map));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            RetInfo retInfo = foundChangeSearchService.findFoundChangeByMembId(tdNtMember.getMemb_id(), Integer.valueOf(map.get("currentPage")), 10);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return RetInfo
     * @Purpose 充值时跳转到第三方界面
     * @version 4.1
     * @time 2015-01-05
     * @author lizhun
     * @Modifier wangzheng on 2017-03-18
     */
    @RequestMapping(value = "/app/1/token/member/recharge", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo recharge(HttpServletRequest request, @RequestBody Map<String, String> map,
                            @RequestHeader(value = "token", required = true) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(map));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            RetInfo retInfo = new RetInfo();
            //参数校验
            String amount_str = map.get("mfchg_change_amount");
            if (amount_str == null || "".equals(amount_str.trim())) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("参数错误：mfchg_change_amount不能为空，mfchg_change_amount=" + amount_str);
                logger.error("参数错误：mfchg_change_amount不能为空，mfchg_change_amount=" + amount_str);
                return retInfo;
            }
            Float amount = null;
            try {
                amount = Float.valueOf(amount_str);
            } catch (NumberFormatException e) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("参数错误：mfchg_change_amount必须为数字，mfchg_change_amount=" + amount_str);
                logger.error("参数错误：mfchg_change_amount必须为数字，mfchg_change_amount=" + amount_str);
                return retInfo;
            }

            String paymentChannel = map.get("channel");
            if (paymentChannel == null || "".equals(paymentChannel.trim())) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("参数错误：channel不能为空，channel=" + paymentChannel);
                logger.error("参数错误：channel不能为空，channel=" + paymentChannel);
                return retInfo;
            }


            retInfo = foundChangeInsertService.insertFoundChange(tdNtMember.getMemb_id(), amount, Ip.getIpAddr(request), paymentChannel);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return RetInfo
     * @Purpose Ping++ WebHooks异步通知
     * @version 1.0
     * @time 2015-01-06
     * @author lizhun
     */
    @RequestMapping(value = "/pay/notify", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    public void notify(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IntrospectionException, InstantiationException, IllegalAccessException {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(params));

            request.setCharacterEncoding("UTF8");
            //获取头部所有信息
            Enumeration headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = (String) headerNames.nextElement();
                String value = request.getHeader(key);
                logger.info(key + ": " + value);
            }
            Map<String, Object> data = (Map<String, Object>) params.get("data");
            Map<String, Object> paymentInfo = (Map<String, Object>) data.get("object");
            logger.info("Ping++ WebHooks异步通知 -->>" + paymentInfo);

            //支付成功
            if ("charge.succeeded".equals(params.get("type"))) {
                foundChangeUpdateService.notify(paymentInfo);
            }
            response.setStatus(200);

            //打印出参
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            response.setStatus(200);
        }
    }

    /**
     * 4.1 已废弃
     *
     * @return RetInfo
     * @Purpose 充值完回调
     * @version 1.0
     * @time 2015-01-05
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/callback", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo callback(@RequestBody Map<String, String> map) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(map));

            RetInfo retInfo = foundChangeSearchService.findFoundChangeByNumber(map.get("mfchg_number"));

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }
}


